package com.jinhuhang.u2.myselfmodule.engine.withdraw;

import android.content.Intent;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.activity.ZSimpleBaseActivity;
import com.jinhuhang.u2.entity.BankBranch;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.entity.WithDrawHandBean;
import com.jinhuhang.u2.entity.WithDrawResult;
import com.jinhuhang.u2.entity.WithDrawTicketBean;
import com.jinhuhang.u2.invertmodule.ResultActivity;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.myselfmodule.adapter.WithDrawTicketAdapter;
import com.jinhuhang.u2.myselfmodule.engine.user.forget.ForgetActivity;
import com.jinhuhang.u2.ui.DefaultWithdrawDialog;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.util.RSAEncryptor;
import com.jinhuhang.u2.util.U2MD5Util;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.logger.Logger;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;

/**
 * Created by OnionMac on 17/9/21.
 */

public class WithDrawActivity extends ZSimpleBaseActivity implements WithDrawContract.View{


    @Bind(R.id.toolbar_back)
    ImageView mToolbarBack;
    @Bind(R.id.toolbar_name)
    TextView mToolbarName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.withdraw_balance)
    TextView mWithdrawBalance;
    @Bind(R.id.withdraw_ll)
    RelativeLayout mWithdrawLl;
    @Bind(R.id.withdraw_bank_icon)
    ImageView mWithdrawBankIcon;
    @Bind(R.id.withdraw_bank_card)
    TextView mWithdrawBankCard;
    @Bind(R.id.recharge_money)
    TextView mRechargeMoney;
    @Bind(R.id.withdraw_edt)
    EditText mWithdrawEdt;
    @Bind(R.id.withdraw_servicemoney)
    TextView mWithdrawServicemoney;
    @Bind(R.id.withdraw_residue)
    TextView mWithdrawResidue;
    @Bind(R.id.withdraw_ticket)
    TextView mWithdrawTicket;
    @Bind(R.id.withdraw_count)
    TextView mWithdrawCount;
    @Bind(R.id.withdraw_arraw)
    ImageView mWithdrawArraw;
    @Bind(R.id.withdraw_recy)
    RecyclerView mWithdrawRecy;
    @Bind(R.id.withdraw_arrivemoney)
    TextView mWithdrawArrivemoney;
    @Bind(R.id.btn_withdraw)
    AppCompatButton mBtnWithdraw;
    @Bind(R.id.withdraw_openrecy)
    RelativeLayout mWithDrawOpenRecy;
    @Bind(R.id.withdraw_line)
    View mWithDrawLine;

    private boolean hasTicket = false;

    private WithDrawContract.Presenter mPresenter;
    private String mLeastWithdraw;
    private List<WithDrawTicketBean> mDatas = new ArrayList<>();
    private WithDrawTicketAdapter mWithDrawTicketAdapter;
    private boolean mIsOpen;
    private int mPreCheck = -1;

    private String mWithDrawMoney;
    private String mPayPassword;
    private String counterFee ="0";
    @Override
    protected void initView() {
        mToolbarName.setText("提现");
        mToolbarBack.setOnClickListener(v -> finish());
    }
    String withdrawMoney;
    @Override
    protected void initData() {
        mWithdrawRecy.setLayoutManager(new LinearLayoutManager(this));
        mWithDrawTicketAdapter = new WithDrawTicketAdapter(R.layout.item_withdraw_ticket,mDatas);
        mWithdrawRecy.setAdapter(mWithDrawTicketAdapter);
        Intent intent = getIntent();
         withdrawMoney = intent.getStringExtra("withdrawMoney");

        mWithdrawBalance.setText(withdrawMoney);
        UserBean user = getUser();
        String cardNo = RSAEncryptor.androidDecryt(user.getCardNo());
        mWithdrawBankCard.setText(UtilsCollection.connectString("(尾号",cardNo.substring(cardNo.length()-4,cardNo.length()),")"));
        BankBranch bankBranch = UtilsCollection.getBankBranch(user.getBankId());
        mWithdrawBankIcon.setImageResource(bankBranch.getBankIcon());

        /**
         * 请求手续费
         */
        mPresenter.getHanding(getUserId());
        mPresenter.getWithDrawTicketList(getUserId());
    }

    @Override
    public void onHandingResult(HttpWrapperList<WithDrawHandBean> o) {
        if(Constant.SUCCESS_CODE == o.code){
            WithDrawHandBean singleData = o.getSingleData();
            mWithdrawServicemoney.setText(UtilsCollection.connectString(singleData.getCounterFee(),"元"));
            mWithdrawResidue.setText(UtilsCollection.connectString("(剩余",singleData.getTimes(),"次免费)"));
            counterFee=singleData.getCounterFee();
            mLeastWithdraw = singleData.getLeastWithdraw();
        }else{
            showMessage(o.getInfo());
        }
    }

    @Override
    public void onTicketReuslt(HttpWrapperList<WithDrawTicketBean> o) {
        if(Constant.SUCCESS_CODE == o.code){
            if(o.getData() != null && o.getData().size() > 0){
                mWithDrawTicketAdapter.addData(o.getData());
                mWithdrawCount.setText(UtilsCollection.connectString("(",o.getData().size()+")"));
                hasTicket = true;
            }else{
                mWithdrawCount.setText("暂无");
                hasTicket = false;
            }
        }else{
            showMessage(o.getInfo());
        }
    }

    @Override
    public void onAutoLoginResult(HttpWrapperList<UserBean> o) {
        if(Constant.SUCCESS_CODE == o.code){
            UserBean singleData = o.getSingleData();
            UserBean oldUser = getUser();
            singleData.setUserName(oldUser.getUserName());
            singleData.setLoginPwd(oldUser.getLoginPwd());
            setUser(singleData);
            Log.v("sdfffffff", RSAEncryptor.androidDecryt(singleData.getCardNo())+"---"+RSAEncryptor.androidDecryt(oldUser.getCardNo()));
            String bankCardNo =  RSAEncryptor.androidDecryt(singleData.getCardNo());
            Map<String,String> map = new HashMap<>();
            map.put("userId",singleData.getUserId());
            map.put("withdrawMoney",mWithDrawMoney);
            map.put("payPassword", U2MD5Util.encryption(mPayPassword));
            map.put("acc_no",bankCardNo);
            if(mPreCheck != -1){
                map.put("id",mDatas.get(mPreCheck).getId());
            }else{
                map.put("id"," ");
            }
            mPresenter.withdraw(map);
        }else{
            showDialog(o.getInfo());
        }
    }

    @Override
    public void onWithDrawResult(WithDrawResult o) {
        if("0000".equals(o.getReturn_code())){
            Intent intent = new Intent(this, ResultActivity.class);
            intent.putExtra(ResultActivity.typestr,Constant.withdraw_success);
            startActivity(intent);
        }else if( o.getReturn_code().equals("9999")){
            String return_msg =  o.getReturn_msg();
            Toast toast = Toast.makeText(getApplicationContext(), return_msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }else if( o.getReturn_code().equals("8888")){
            MyDialog.showDialog("交易密码不正确，请重新输入",this);
        }else{
            Intent intent = new Intent(this, ResultActivity.class);
            intent.putExtra(ResultActivity.typestr,Constant.withdraw_fail);
            startActivity(intent);
        }
    }

    @Override
    protected void initListener() {
        mWithDrawOpenRecy.setOnClickListener(v -> {
            if(!hasTicket){
                UtilsCollection.getSingleDialog(this,"温馨提示","您暂时没有提现券","确定",null);
                return;
            }
            mIsOpen = !mIsOpen;
            if(mIsOpen){
                mWithDrawLine.setVisibility(View.VISIBLE);
                mWithdrawArraw.setImageResource(R.drawable.touzi_downbutton_gray);
                mWithdrawRecy.setVisibility(View.VISIBLE);
            }else{
                mWithDrawLine.setVisibility(View.GONE);
                mWithdrawArraw.setImageResource(R.drawable.account_arrows);
                mWithdrawRecy.setVisibility(View.GONE);
            }
        });
        mWithDrawTicketAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()){
                case R.id.item_withdraw_ticket_cb:
                    for (int i = 0; i < mDatas.size(); i++) {
                        if(i == position){
                            mDatas.get(i).setCheck(true);
                            mPreCheck = position;
                        }else{
                            mDatas.get(i).setCheck(false);
                        }
                    }
                    mWithDrawTicketAdapter.notifyDataSetChanged();
                    break;
            }
        });

        mWithdrawEdt.addTextChangedListener(new TextWatcher() {
            private int selectionStart;
            private int selectionEnd;
            private CharSequence temp;
            public boolean isOnlyPointNumber(String number) {
                Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,2}$");
                Matcher matcher = pattern.matcher(number);
                return matcher.matches();
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                if(TextUtils.isEmpty(s.toString())){
                    mWithdrawArrivemoney.setText("0.00");
                    return;
                }
                selectionStart = mWithdrawEdt.getSelectionStart();
                selectionEnd = mWithdrawEdt.getSelectionEnd();

                if (!isOnlyPointNumber(mWithdrawEdt.getText().toString())){
                    //删除多余输入的字
                    s.delete(selectionStart - 1, selectionEnd);
                    mWithdrawEdt.setText(s);
                    mWithdrawEdt.setSelection(s.length());
                }
                DecimalFormat df = new DecimalFormat("0.00");
                String format = df.format(Double.parseDouble(s.toString()));
                mWithdrawArrivemoney.setText(UtilsCollection.connectString(format,"元"));
            }
        });

        mBtnWithdraw.setOnClickListener(v -> {
            String money = mWithdrawEdt.getText().toString();
            mWithDrawMoney = money;
            if(TextUtils.isEmpty(money)){
                MyDialog.showDialog("请输入提现金额",this);
              //  UtilsCollection.getSingleDialog(this,"温馨提示","请输入提现金额","确定",null).show();
                return;
            }

            if(!UtilsCollection.isNumber(money)){
                MyDialog.showDialog("请输入正确的金额",this);
            //    UtilsCollection.getSingleDialog(this,"温馨提示","请输入正确的金额","确定",null).show();
                return;
            }
            BigDecimal  withdrawMoneyDecimal =  new BigDecimal(mWithDrawMoney);
            if(new BigDecimal(mWithDrawMoney).compareTo(new BigDecimal(withdrawMoney))>0){
                Toast toast = Toast.makeText(getApplicationContext(), "账户余额不足！", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return ;
            }
            if(withdrawMoneyDecimal.compareTo(new BigDecimal(counterFee))<1){
                Toast toast = Toast.makeText(getApplicationContext(), "提现金额必须大于"+counterFee+"元", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return ;
            }

            if(withdrawMoneyDecimal.compareTo(new BigDecimal(mLeastWithdraw))<0){
                Toast toast = Toast.makeText(getApplicationContext(), "提现金额必须大于"+mLeastWithdraw+"元", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return ;
            }
            DefaultWithdrawDialog defaultWithdrawDialog = new DefaultWithdrawDialog(this);
            defaultWithdrawDialog.show();
            defaultWithdrawDialog.setMoney(mWithdrawEdt.getText().toString());
            defaultWithdrawDialog.setOnNormalDialogLeftListener(() -> {
                Intent intent = new Intent(this, ForgetActivity.class);
                intent.putExtra(ForgetActivity.FORGET_TYPE,ForgetActivity.FORGET_TYPE_JIAOYI);
                startActivity(intent);
            });
            defaultWithdrawDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
                @Override
                public void onLeft() {

                }

                @Override
                public void onRight() {
                    String pwd = defaultWithdrawDialog.getPwd();
                    if(TextUtils.isEmpty(pwd)){
                        showMessage("交易密码不能为空?");
                    }else{
                        mPayPassword = pwd;
                        autoLogin();
                    }
                }
            });
        });
    }

    /**
     * 下一步操作
     */
    private void autoLogin() {
        UserBean user = getUser();
        mPresenter.autoLogin(user.getUserId(),user.getUserName());
    }

    @Override
    protected void attachPre() {
        mPresenter = new WithPresenter(this,mCompositeSubscription);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_withdraw;
    }

}
